import { createApp } from 'vue'
import App from './App.vue' 
import router from './router'
import '@/assets/styles/backgrounds.css';
import { tokenApi } from './api';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

const app = createApp(App)

// 添加全局变量
app.config.globalProperties.$globals = {
    ROLE: 'farmer'
}

// 初始化 token
const initToken = async () => {
  try {
    const response = await tokenApi.getToken();
    tokenApi.saveToken(response.token, response.expires_at);
    //用于查看token
    //console.log('token', response);
  } catch (error) {
    console.error('Failed to initialize token:', error);
  }
};

// 更新 token
const updateToken = async () => {
  try {
    const response = await tokenApi.updateToken();
    tokenApi.saveToken(response.new_token, response.expires_at);
  } catch (error) {
    console.error('Failed to update token:', error);
    // 如果更新失败，尝试重新获取 token
    await initToken();
  }
};

// 检查并更新 token
const checkAndUpdateToken = async () => {
  if (tokenApi.isTokenExpired()) {
    await updateToken();
  }
};

// 在应用启动时初始化 token
initToken();

// 设置定时检查 token 是否过期（每分钟检查一次）
setInterval(checkAndUpdateToken, 60000);

app.use(router)
app.use(ElementPlus)
app.mount('#app') 